const express = require('express');
const fs = require('fs');
var app = express();
const bodyParser = require("body-parser");
const timeFun = require('./mymodules/getDate');


app.use(express.static('./public'));
app.use('/bootstrap/', express.static('./node_modules/bootstrap3/dist/'));
app.use('/jquery/', express.static('./node_modules/jQuery/tmp/'));
app.engine('html', require("express-art-template"));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json())

//渲染首页
app.get('/', function (req, res) {
    fs.readFile('./data/data.json', 'utf-8', function (error, data) {
        res.render('./index.html', {
            list: JSON.parse(data)
        });
    })
});
app.get('/index.html', function (req, res) {
    fs.readFile('./data/data.json', 'utf-8', function (error, data) {
        res.render('./index.html', {
            list: JSON.parse(data)
        });
    })
});
app.get('/post.html', function (req, res) {
    fs.readFile('./views/post.html', 'utf-8', function (error, data) {
        res.end(data);
    })
});
//处理post数据
app.post('/postInputData', function (req, res) {
    //res.body  获取post的数据
    //console.log(req.body.name);
    // console.log(timeFun());
    //  console.log(JSON.stringify(req.body));
    fs.readFile('./data/data.json', 'utf-8', function (error, data) {
        let name = req.body.name;
        let time = timeFun();
        let con = req.body.con;
        let conPre = JSON.parse(data);
        //     console.log(conPre);
        let writeStr = { "id": conPre.length + 1, "name": name, "time": time, "con": con };
        //       console.log(writeStr);
        conPre.push(writeStr);
        // console.log(conPre);
        // console.log(JSON.stringify(conPre));
        fs.writeFile("./data/data.json", JSON.stringify(conPre), function (error, data) {
            if (!error) {
                console.log("write success!");
                res.end('<script>location.href = "/index.html"</script>')
            };
        });
    })
});


app.listen(8081, function () {
    console.log("running.............");
})